package com.ailesson.common.handler;

import com.ailesson.common.base.BaseEntity;
import com.ailesson.common.util.web.WebFrameworkUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import java.util.Objects;

public class DefaultDBFieldHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity){
            BaseEntity base = (BaseEntity)metaObject.getOriginalObject();
            LocalDateTime now = LocalDateTime.now();
            if (Objects.isNull(base.getCreateTime())){
                base.setCreateTime(now);
            }
            if (Objects.isNull(base.getUpdateTime())){
                base.setUpdateTime(now);
            }
            Long userId = WebFrameworkUtils.getLoginUserId();
            if (Objects.nonNull(userId) && Objects.isNull(base.getCreator())){
                base.setCreator(userId+"");
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时间为空，则以当前时间为更新时间
        Object modifyTime = getFieldValByName("updateTime", metaObject);
        if (Objects.isNull(modifyTime)) {
            setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }

        // 当前登录用户不为空，更新人为空，则当前登录用户为更新人
        Object modifier = getFieldValByName("updater", metaObject);
        Long userId = WebFrameworkUtils.getLoginUserId();
        if (Objects.nonNull(userId) && Objects.isNull(modifier)) {
            setFieldValByName("updater", userId.toString(), metaObject);
        }
    }
}
